<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Exception\Handler;

use App\Constants\System\HttpCode;
use App\Traits\ApiResponseTrait;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\Logger\LoggerFactory;
use Psr\Http\Message\ResponseInterface;
use Qbhy\HyperfAuth\Exception\AuthException;
use Qbhy\SimpleJwt\Exceptions\TokenExpiredException;
use Throwable;
use function Hyperf\Support\env;

class AppExceptionHandler extends ExceptionHandler
{

    use ApiResponseTrait;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;
    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get('default');
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
        $this->logger->error($throwable->getTraceAsString());
        if($throwable instanceof AuthException || $throwable instanceof TokenExpiredException)
        {
            $this->setHttpCode(HttpCode::UNAUTHORIZED);
            return $this->fail($throwable->getMessage(),$throwable->getCode())->withStatus(HttpCode::UNAUTHORIZED);
        }
        $errorMsg = $throwable->getMessage();
        if(env("APP_ENV") == 'prod')
        {
            $errorMsg = "内部错误，联系管理员处理";
        }
        return $this->fail($errorMsg)->withStatus(HttpCode::BAD_REQUEST);
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
